package me.numark;

import com.google.gson.Gson;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.ProfileResponse;
import me.numark.model.User;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.net.UploadImageRequest;
import me.numark.utils.ImageUtils;
import me.numark.utils.Settings;
import me.numark.view.CircleImageView;


public class MyProfileActivity extends AuthenticatorActivity implements View.OnClickListener {

    @InjectView(R.id.back)
    View back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.avatar)
    CircleImageView avatar;

    @InjectView(R.id.change_avatar)
    TextView changeAvatar;

    @InjectView(R.id.right_text)
    TextView rightButton;

    @InjectView(R.id.nick)
    TextView nick;

    @InjectView(R.id.gender)
    TextView gender;

    @InjectView(R.id.desc)
    TextView desc;

    @InjectView(R.id.email)
    TextView email;

    @InjectView(R.id.bind_email)
    Button bindEmail;

    @InjectView(R.id.unbind_email)
    Button unbindEmail;

    @InjectView(R.id.mobile)
    TextView mobile;

    @InjectView(R.id.bind_mobile)
    Button bindMobile;

    @InjectView(R.id.unbind_mobile)
    Button unbindMobile;

    @InjectView(R.id.weibo)
    TextView weibo;

    @InjectView(R.id.bind_weibo)
    Button bindWeibo;

    @InjectView(R.id.unbind_weibo)
    Button unbindWeibo;

    @InjectView(R.id.qq)
    TextView qq;

    @InjectView(R.id.bind_qq)
    Button bindQQ;

    @InjectView(R.id.unbind_qq)
    Button unbindQQ;

    private User mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);
        ButterKnife.inject(this);
        mUser = new Gson().fromJson(Settings.getProfile(), User.class);
        initView();
    }

    private void initView() {
        back.setOnClickListener(this);
        title.setText(R.string.my_info);
        rightButton.setText(R.string.finish);
        rightButton.setOnClickListener(this);
        if (!TextUtils.isEmpty(mUser.pic)) {
            Picasso.with(this).load(mUser.pic).into(avatar);
        }
        changeAvatar.setOnClickListener(this);
        nick.setText(mUser.nick);
        nick.setOnClickListener(this);
        gender.setText(mUser.getGenderText());
        gender.setOnClickListener(this);
        desc.setText(mUser.des);
        desc.setOnClickListener(this);
        if (TextUtils.isEmpty(mUser.email)) {
            bindEmail.setVisibility(View.VISIBLE);
            unbindEmail.setVisibility(View.GONE);
        } else {
            email.setText(mUser.email);
            bindEmail.setVisibility(View.GONE);
            unbindEmail.setVisibility(View.VISIBLE);
        }
        bindEmail.setOnClickListener(this);
        unbindEmail.setOnClickListener(this);
        if (TextUtils.isEmpty(mUser.phone)) {
            bindMobile.setVisibility(View.VISIBLE);
            unbindMobile.setVisibility(View.GONE);
        } else {
            mobile.setText(mUser.phone);
            bindMobile.setVisibility(View.GONE);
            unbindMobile.setVisibility(View.VISIBLE);
        }
        bindMobile.setOnClickListener(this);
        unbindMobile.setOnClickListener(this);
        if (TextUtils.isEmpty(mUser.weibo)) {
            bindWeibo.setVisibility(View.VISIBLE);
            unbindWeibo.setVisibility(View.GONE);
        } else {
            weibo.setText(mUser.weibo);
            bindWeibo.setVisibility(View.GONE);
            unbindWeibo.setVisibility(View.VISIBLE);
        }
        bindWeibo.setOnClickListener(this);
        unbindWeibo.setOnClickListener(this);
        if (TextUtils.isEmpty(mUser.QQ)) {
            bindQQ.setVisibility(View.VISIBLE);
            unbindQQ.setVisibility(View.GONE);
        } else {
            qq.setText(mUser.QQ);
            bindQQ.setVisibility(View.GONE);
            unbindQQ.setVisibility(View.VISIBLE);
        }
        bindQQ.setOnClickListener(this);
        unbindQQ.setOnClickListener(this);
        mSex = mUser.sex;
        mDescription = mUser.des;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_text:
                if (avatarImage == null) {
                    uploadProfile();
                } else {
                    uploadAvatar(avatarImage);
                }
                showProgress();
                break;
            case R.id.change_avatar:
                ImageUtils.takeOrChoosePhoto(this, ImageUtils.TAKE_OR_CHOOSE_PHOTO);
                break;
            case R.id.nick:
                break;
            case R.id.gender:
                break;
            case R.id.desc:
                break;
            case R.id.bind_qq:
                break;
            case R.id.unbind_qq:
                break;
            case R.id.bind_email:
                break;
            case R.id.unbind_email:
                break;
            case R.id.bind_weibo:
                mSsoHandler.authorize(this);
                break;
            case R.id.unbind_weibo:
                doBind(TYPE_WEIBO, false);
                break;
            case R.id.bind_mobile:
                break;
            case R.id.unbind_mobile:
                break;
            default:
                break;
        }
    }

    private static final int TYPE_MOBILE = 0;

    private static final int TYPE_EMAIL = 1;

    private static final int TYPE_WEIBO = 2;

    private static final int TYPE_QQ = 3;

    private void doBind(int type, boolean bind) {
        String url = getBindUrl(type);
        if (url == null) {
            return;
        }
        Map<String, String> body = new HashMap<String, String>();
        body.put("type", bind ? "bind" : "unbind");
        body.putAll(getBindParams(type, bind));
        GsonRequest<ProfileResponse> request = new GsonRequest<ProfileResponse>(url,
                Request.Method.POST, ProfileResponse.class, true, null,
                new Response.Listener<ProfileResponse>() {
                    @Override
                    public void onResponse(ProfileResponse response) {
                        dismissProgress();
                        if (response.ret) {
                            Toast.makeText(MyProfileActivity.this, R.string.bind_success,
                                    Toast.LENGTH_SHORT).show();
                            if (response.data != null) {
                                Settings.saveProfile(response.data.toString());
                                mUser = response.data;
                                initView();
                            }
                        } else {
                            Toast.makeText(MyProfileActivity.this, response.msg, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissProgress();
                Toast.makeText(MyProfileActivity.this, R.string.generic_network_error,
                        Toast.LENGTH_SHORT).show();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        showProgress();
    }

    private Map<String, String> getBindParams(int type, boolean bind) {
        Map<String, String> params = new HashMap<String, String>();
        switch (type) {
            case TYPE_MOBILE:
                break;
            case TYPE_QQ:
                params.put("uid", Settings.getQQUid());
                if (bind) {
                    params.put("token", Settings.readQQAccessToken().getToken());
                }
                break;
            case TYPE_WEIBO:
                params.put("uid", Settings.getWeiboUid());
                if (bind) {
                    params.put("token", Settings.readWeiboAccessToken().getToken());
                }
                break;
            case TYPE_EMAIL:
                break;
        }
        return params;
    }

    private String getBindUrl(int type) {
        switch (type) {
            case TYPE_MOBILE:
                return String.format(NetworkConstants.BIND_MOBILE_URL, Settings.getUid());
            case TYPE_EMAIL:
                return String.format(NetworkConstants.BIND_EMAIL_URL, Settings.getUid());
            case TYPE_WEIBO:
                return String.format(NetworkConstants.BIND_WEIBO_URL, Settings.getUid());
            case TYPE_QQ:
                return String.format(NetworkConstants.BIND_QQ_URL, Settings.getUid());
            default:
                return null;
        }

    }

    private Bitmap avatarImage = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case ImageUtils.TAKE_OR_CHOOSE_PHOTO:
                File f = ImageUtils.getPhotoFromResult(this, data);
                ImageUtils.doCropPhoto(this, f);
                break;
            case ImageUtils.PHOTO_PICKED_WITH_DATA:
                avatarImage = ImageUtils.getCroppedImage();
                avatar.setImageBitmap(avatarImage);
                avatar.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void uploadAvatar(final Bitmap avatarImage) {
        String uid = Settings.getUid();
        String url = String.format(NetworkConstants.UPDATE_AVATAR_URL, uid);
        UploadImageRequest request = new UploadImageRequest(this, url, "user_pic",
                avatarImage, new UploadImageRequest.ResultListener() {
            @Override
            public void onSuccess(String msg) {
                uploadProfile();
            }

            @Override
            public void onFailure(String msg) {
                dismissProgress();
                Toast.makeText(MyProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
        request.execute();
    }

    private int mSex;

    private String mDescription;

    private void uploadProfile() {
        String url = String.format(NetworkConstants.UPDATE_PROFILE_URL, Settings.getUid());
        Map<String, String> body = new HashMap<String, String>();
        body.put("sex", Integer.toString(mSex));
        body.put("des", mDescription);
        GsonRequest<ProfileResponse> request = new GsonRequest<ProfileResponse>(url,
                Request.Method.POST, ProfileResponse.class, true, body,
                new Response.Listener<ProfileResponse>() {
                    @Override
                    public void onResponse(ProfileResponse response) {
                        dismissProgress();
                        if (response.ret) {
                            Settings.saveProfile(response.data.toString());
                            mUser = response.data;
                            initView();
                        } else {
                            Toast.makeText(MyProfileActivity.this, response.msg, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissProgress();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }
}
